#include"mystdio.h"
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define MODE 0666

// "w" "r" "a"
_FILE* _fopen(const char* pathname, const char* mode)
{
	int flag = 0;
	int fd = -1;
	if(strcmp(mode, "w") == 0)
	{
		flag = (O_CREAT|O_WRONLY|O_TRUNC);
		fd = open(pathname, flag, MODE);
	}
	else if(strcmp(mode, "a") == 0)
	{
		flag = (O_CREAT|O_WRONLY|O_APPEND);
		fd = open(pathname, flag, MODE);
	}
	else if(strcmp(mode, "r") == 0)
	{
		flag = (O_RDONLY);
		fd = open(pathname, flag);
	}
	else return NULL; //选项错误
	
	if(fd < 0) return NULL; //打开失败
	
	_FILE* fp = (_FILE*)malloc(sizeof(_FILE)); //创建对象
	
	fp->fileno = fd;
	fp->pos = 0;
	fp->buffer_mode = FLUSH_LINE; //固定行刷新
	return fp;
}


int _fwrite(_FILE* fp, const char* mes, int len)
{
	//不考虑异常和局部不够
	memcpy(&fp->outbuffer[fp->pos], mes, len);
	fp->pos += len;
	int tmp = 0;
	if(fp->buffer_mode & FLUSH_NOW)
	{
		write(fp->fileno, fp->outbuffer, fp->pos);
		tmp = fp->pos;
		fp->pos = 0;
	}
	else if(fp->buffer_mode & FLUSH_LINE)
	{
		// "abcd\n"
		if(fp->outbuffer[fp->pos - 1] == '\n')
		{
			write(fp->fileno, fp->outbuffer, fp->pos);
			tmp = fp->pos;
			fp->pos = 0;
		}
	}
	else if(fp->buffer_mode & FLUSH_ALL)
	{
		if(fp->pos == SIZE)
		{
			write(fp->fileno, fp->outbuffer, fp->pos);
			tmp = fp->pos;
			fp->pos = 0;
		}
	}

	return tmp;
}

void _fflush(_FILE* fp)
{
	if(fp->pos == 0) return;
	
	write(fp->fileno, fp->outbuffer, fp->pos);
	fp->pos = 0;
}


void _fclose(_FILE* fp)
{
	if(fp == NULL) return;
	_fflush(fp);
	close(fp->fileno);
	free(fp);
}
